import { HttpConfig } from './http';
import { ObjectUtil } from '../utils/ObjectUtil';
import { AxiosRequestConfig } from 'axios';

export const ignoreClientError = (status: number): boolean =>
	(status >= 200 && status < 300) || (status >= 400 && status < 500);

export const ignoreAllError = (): boolean => true;

export const reverseStatus = (status: number): boolean =>
	status >= 400 && status < 500;

let defaultHttpConfig: HttpConfig = {
	id: Symbol.for('Api'),
};

export const HttpConfigSource = {
	/**
	 * @author 戴俊明 <idaijunming@163.com>
	 * @description 修改默认 HTTP 配置
	 * @date 2020/3/12 17:00
	 **/
	setSource: (config: HttpConfig): void => {
		defaultHttpConfig = config;
	},

	/**
	 * @author 戴俊明 <idaijunming@163.com>
	 * @description 获取默认 HTTP 配置
	 * @date 2020/3/12 17:01
	 **/
	getSource: (): HttpConfig => defaultHttpConfig,

	/**
	 * @author 戴俊明 <idaijunming@163.com>
	 * @description 将 config 与默认 HTTP 配置合并并保存
	 * @date 2020/3/12 17:01
	 **/
	upgrade: (config: AxiosRequestConfig): void => {
		defaultHttpConfig = ObjectUtil.assign(
			defaultHttpConfig,
			config
		) as HttpConfig;
	},

	/**
	 * @author 戴俊明 <idaijunming@163.com>
	 * @description 将 config 与默认 HTTP 配置合并
	 * @date 2020/3/12 17:01
	 **/
	merge: (config?: AxiosRequestConfig): HttpConfig => {
		if (config) {
			return ObjectUtil.assign(defaultHttpConfig, config) as HttpConfig;
		}
		return defaultHttpConfig;
	},
};
